import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
import {
    MessageBox,
    Message
} from 'element-ui'
import routes from "./route.js";
// 进度条插件
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// 导入token
import {
    getAccessToken,
    getRefreshToken,
    setAccessToken
} from "@/utils/auth"
import {
    Refresh
} from "@/api/modules/user"
// 重写push|replace方法,使编程式导航不会报错
// 保存Push|replace方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function(location, resolve, reject) {
    // 如果存在回调信息就调用push方法,如果不存在就返回回调信息
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(
            this,
            location,
            () => {},
            () => {}
        );
    }
};
VueRouter.prototype.replace = function(location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(
            this,
            location,
            () => {},
            () => {}
        );
    }
};

const createRouter = () => new VueRouter({
    // mode: "history",
    // base: process.env.BASE_URL,
    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return {
                selector: to.hash,
                behavior: 'smooth'
            };
        } else {
            return { x: 0, y: 0 };
        }
    },
    routes,
});
const router = createRouter();
router.beforeEach(async(to, from, next) => {
    const accessToken = getAccessToken();
    NProgress.start()
        // 判断是否需要登录校验
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // 如果没有AccessToken，尝试刷新令牌
        if (!accessToken) {
            try {
                const response = await Refresh();
                console.log("refreshData", response)
                if (response.status == 200) {
                    // 刷新成功，重新设置AccessToken
                    setAccessToken(response.data.AccessToken);
                    next();
                } else {
                    console.log("用户国企")
                        // 刷新失败或令牌过期，跳转到登录页面
                    redirectToLogin(next);
                }
            } catch (error) {
                // 刷新请求失败，跳转到登录页面
                console.log("error")
                redirectToLogin(next);
            }
        } else {
            // 有AccessToken，继续导航
            next();
        }
    } else {
        // 不需要登录校验的页面，直接导航
        next();
    }
});

export function redirectToLogin(next) {
    next("/login");
    // 或者使用下面的方式跳转到登录页面
    // next({ path: "/login" });
}


// 路由后置守卫
router.afterEach(() => {
    // Complete the progress bar
    NProgress.done();
});




// 重置路由历史记录
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // the relevant part
}

export default router;